<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>按顺序完成异步操作</title>
</head>
<body>
    <h1>实例：按顺序完成异步操作</h1>

    <script>
        // 模拟异步请求
        function logInOrder(urls) {
            // 并发获取远程URL
            const textPromises = urls.map(url => {
                return fetch(url).then(response => response.text());
            });

            // 按顺序输出
            textPromises.reduce((chain, textPromise) => {
                return chain.then(() => textPromise)
                    .then(text => console.log(text));
            }, Promise.resolve());
        }

        // 使用async函数实现
        async function logInOrderAsync(urls) {
            // 并发读取远程URL
            const textPromises = urls.map(async url => {
                const response = await fetch(url);
                return response.text();
            });

            // 按顺序输出
            for (const textPromise of textPromises) {
                console.log(await textPromise);
            }
        }

        // 实际应用示例
        const mockFetch = (url) => {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(`来自 ${url} 的数据`);
                }, Math.random() * 1000);
            });
        };

        // 顺序执行
        async function sequentialExecution(urls) {
            console.log('开始顺序执行');
            for (const url of urls) {
                const data = await mockFetch(url);
                console.log(data);
            }
            console.log('顺序执行完成');
        }

        // 并行执行但按顺序输出
        async function parallelExecution(urls) {
            console.log('开始并行执行');
            const promises = urls.map(mockFetch);
            for (const promise of promises) {
                const data = await promise;
                console.log(data);
            }
            console.log('并行执行完成');
        }

        // 测试
        const urls = [
            '/api/data1',
            '/api/data2',
            '/api/data3'
        ];

        sequentialExecution(urls);
        parallelExecution(urls);
    </script>
</body>
</html> 